package com.study.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.study.dao.RoleDao;
import com.study.model.AuthConfig;
import com.study.model.Role;
import com.study.service.RoleService;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDao roleDao;

	@Override
	public List<Role> getPaginate(Map<String,Object> paramMap) {
		return roleDao.getPaginate(paramMap);
	}

	@Override
	public int getTotal(String searchValue) {
		List<Role> list = roleDao.getTotal(searchValue);
		if (list != null) {
			return list.size();
		}
		return 0;
	}

	@Override
	@Transactional
	public void save(Role role) {
		roleDao.save(role);
		String[] auths = role.getSelectKeys().split(",");
		for(int i=0;i<auths.length;i++){
			role.setAuthid(auths[i]);
			roleDao.saveRoleAuth(role);
		}
	}

	@Override
	public Role get(String id) {
		return roleDao.get(id);
	}

	@Override
	@Transactional
	public void update(Role role) {
		roleDao.update(role);
		roleDao.removeRoleAuth(role);
		String[] auths = role.getSelectKeys().split(",");
		for(int i=0;i<auths.length;i++){
			role.setAuthid(auths[i]);
			role.setRoleid(role.getId().toString());
			roleDao.saveRoleAuth(role);
		}
	}

	@Override
	public void remove(String ids) {
		String[] idsArr = ids.split(",");
		Role role = new Role();
		for(int i=0;i<idsArr.length;i++){
			roleDao.remove(idsArr[i]);
			role.setId(Long.valueOf(idsArr[i]));
			roleDao.removeRoleAuth(role);
		}
	}

	@Override
	public List<Role> getAllRole() {
		return roleDao.getAllRole();
	}

	@Override
	public List<AuthConfig> getAuthconfigs() {
		return roleDao.getAuthconfigs();
	}

	@Override
	public List<Role> getByRoleId(Long roleId) {
		return roleDao.getByRoleId(roleId);
	}

	@Override
	public Role isExistByName(String roleName) {
		return roleDao.isExistByName(roleName);
	}
}